/**
 * 
 */
package lvtu.opencv.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import lvtu.opencv.bean.Pic;
import lvtu.opencv.util.LvtuOpencvUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DBUtil {
    private static final Logger logger = LoggerFactory.getLogger(DBUtil.class);

    /** --------返回插入的图片数----------- */
    public static List<Pic> getPic() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Pic> re = new ArrayList<Pic>();
        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT id,url FROM record where is_face= ? limit ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, LvtuOpencvUtil.NO_CHECKED);
            pstmt.setInt(2, LvtuOpencvUtil.LIMIT_NUM);
            ResultSet result = pstmt.executeQuery();
            if(result!=null){
            	Pic pic = null;
            	while(result.next()){
            		pic = new Pic();
            		pic.setId(result.getLong("id"));
            		pic.setUrl(result.getString("url"));
            		re.add(pic);
            	}
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            JdbcUtils.release(conn, pstmt, rs);
        }
        return re;
    }

    /** ------- 跟新数据----------- */
    public static int updatePic(ConcurrentLinkedQueue<Pic> list,boolean has_face) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int affectRowCount = 0;
        try {
        	if(list!=null && list.size() > 0){
				conn = JdbcUtils.getConnection();
				String sql = "UPDATE record set is_face = ? where id = ? ";
				pstmt = conn.prepareStatement(sql);
				if (has_face) {
					pstmt.setInt(1, LvtuOpencvUtil.CHECK_HAS_FACE);
				}else{
					pstmt.setInt(1, LvtuOpencvUtil.CHECK_NO_FACE);
				}
				for (Pic pic : list) {
					pstmt.setLong(2, pic.getId());
					pstmt.addBatch();
				}
				int[] result = pstmt.executeBatch();
                 logger.info("检测更新数据" + result.length + "条");
        	}
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            JdbcUtils.release(conn, pstmt, rs);
        }

        return affectRowCount;
    }
}
